﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Windows.Forms;

namespace RMS.DB
{
    internal class InventoryMng : DBController
    {
        public int ImportProducts(List<Inventory> productList)
        {
            int successResultCount = 0;
            foreach (Inventory item in productList)
            {
                try
                {
                    if (IsExist(item))
                    {
                        int oldQty = GetInventoryByElements(item.ID).Quantity.Value;

                        item.Quantity += oldQty;

                        UpdateItem(item.Name, item.Volume.Value, item.ID, item.SupplierID, item.Category, item.StyleNo, item.Quantity.Value, DateTime.Now, item.Description, item.SalePrice.Value, item.Weight.Value, item.ImportPrice.Value, item.Image, item.TotalPrice.Value, item.InvoiceNo, item.MemoNo, item.ItemNo, item.SupplierID);
                    }
                    else
                    {
                        AddInventoryItem(item.Name, item.Volume.Value, item.ID, item.SupplierID, item.Category, item.StyleNo, item.Quantity.Value, DateTime.Now, item.Description, item.SalePrice.Value, item.Weight.Value, item.ImportPrice.Value, item.Image, item.TotalPrice.Value, item.InvoiceNo, item.MemoNo, item.ItemNo, item.SupplierID);
                    }
                }
                catch (Exception)
                {
                }

                successResultCount += 1;
            }

            return successResultCount;
        }

        public List<Inventory> GetAllInventory()
        {
            var listItems = new List<Inventory>();
            try
            {
                IOrderedQueryable<Inventory> query = from item in DataEntities.Inventories
                                                     orderby item.Quantity
                                                     select item;

                listItems = query.ToList();
            }
            catch (Exception ex)
            {
                MessageBox.Show(Constants.Msg.ConnectError);
            }

            return listItems;
        }

        public List<string> GetAllItemsId()
        {
            var items = GetAllInventory();
            if (items.Count == 0)
                return null;
            return items.Select(item => item.ID).ToList();
        }

        public List<Inventory> GetRemainInStockInventory()
        {
            var listItems = new List<Inventory>();
            try
            {
                IOrderedQueryable<Inventory> query = from item in DataEntities.Inventories
                                                     where item.Quantity > 0
                                                     orderby item.Quantity
                                                     select item;

                listItems = query.ToList();
            }
            catch (Exception ex)
            {
                MessageBox.Show(Constants.Msg.ConnectError);
            }

            return listItems;
        }

        public List<Inventory> GetInventoryByElements(string id, string category, string supplier)
        {
            var allItem = new List<Inventory>();
            try
            {
                allItem = GetAllInventory();

                if (!string.IsNullOrEmpty(id))
                {
                    IEnumerable<Inventory> query1 = from item in allItem
                                                    where item.ID.ToLower().Contains(id.ToLower())
                                                    select item;
                    allItem = query1.ToList();
                }

                if (!string.IsNullOrEmpty(category))
                {
                    IEnumerable<Inventory> query2 = from item in allItem
                                                    where item.Category.ToLower().Contains(category.ToLower())
                                                    select item;
                    allItem = query2.ToList();
                }
                if (!string.IsNullOrEmpty(supplier))
                {
                    IEnumerable<Inventory> query3 = from item in allItem
                                                    where item.SupplierID.ToLower().Contains(supplier.ToLower())
                                                    select item;
                    allItem = query3.ToList();
                }
            }
            catch (Exception)
            {
                MessageBox.Show(Constants.Msg.ConnectError);
            }

            return allItem;
        }

        public List<Inventory> GetAvailInventoryByElements(string id, string category, string supplier)
        {
            var allItem = new List<Inventory>();
            try
            {
                IQueryable<Inventory> query = from item in DataEntities.Inventories
                                              where item.Quantity > 0
                                              select item;
                allItem = query.ToList();

                if (!string.IsNullOrEmpty(id))
                {
                    IEnumerable<Inventory> query1 = from item in allItem
                                                    where item.ID.ToLower().Contains(id.ToLower())
                                                    select item;
                    allItem = query1.ToList();
                }

                if (!string.IsNullOrEmpty(category))
                {
                    IEnumerable<Inventory> query2 = from item in allItem
                                                    where item.Category.ToLower().Contains(category.ToLower())
                                                    select item;
                    allItem = query2.ToList();
                }
                if (!string.IsNullOrEmpty(supplier))
                {
                    IEnumerable<Inventory> query3 = from item in allItem
                                                    where item.SupplierID.ToLower().Contains(supplier.ToLower())
                                                    select item;
                    allItem = query3.ToList();
                }
            }
            catch (Exception)
            {
                MessageBox.Show(Constants.Msg.ConnectError);
            }

            return allItem;
        }

        public Inventory GetInventoryByElements(string id)
        {
            var inventory = new Inventory();
            try
            {
                IQueryable<Inventory> query = from item in DataEntities.Inventories
                                              orderby item.Quantity
                                              where item.ID == id
                                              select item;

                inventory = query.FirstOrDefault();
            }
            catch (Exception)
            {
                MessageBox.Show(Constants.Msg.ConnectError);
            }

            return inventory;
        }

        public bool AddInventoryItem(string name, decimal volume, string id, string supplier, string cate, string styleNo, int quantity, DateTime date, string desc,
        decimal SalePrice, decimal weight, decimal unitCost, string imageName, decimal totalPrice, string invoiceNo, string memoNo, string itemNo, string supStyleNo)
        {
            if (string.IsNullOrEmpty(id))
            {
                MessageBox.Show(Constants.Msg.FieldRequired);
                return false;
            }
            var item = new Inventory { ID = id,
            SupplierID = supplier,
            Category = cate,
            StyleId = styleNo,
            Quantity = quantity,
            Date = date,
            Description = desc,
            SalePrice = SalePrice,
            Weight = weight,
            ImportPrice = unitCost,
            Image = string.IsNullOrEmpty(imageName) || imageName.Equals("noimage") ? null : imageName,
            TotalPrice = totalPrice,
            InvoiceNo = invoiceNo,
            MemoNo = memoNo,
            ItemNo = itemNo,
            StyleNo = supStyleNo,
            Name = name,
            Volume = volume };

            return Save(item);
        }

        public bool Save(Inventory input)
        {
            try
            {
                if (IsExist(input)) // If existed, update quantity
                {
                    if (MessageBox.Show(Constants.Msg.ItemExist, "Chú ý", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        AddDuplicatedItem(input.ID, Convert.ToInt32(input.Quantity));
                    }
                    else
                        return false;
                }
                else // if not existed, add new item
                {
                    DataEntities.AddToInventories(input);
                    DataEntities.SaveChanges();
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(Constants.Msg.ConnectError);
                return false;
            }
        }
        public bool UpdateItem(string name, decimal volume, string id, string supplier, string cate, string styleNo, int quantity, DateTime date, string desc,
        decimal SalePrice, decimal weight, decimal unitCost, string image, decimal totalPrice, string invoiceNo, string memoNo, string itemNo, string supStyleNo)
        {
            try
            {
                var inv = new Inventory();
                inv = GetInventoryByElements(id);
                if (inv == null)
                {
                    //MessageBox.Show(Constants.Msg.NotItemExist);
                    return false;
                }
                inv.SupplierID = supplier;
                inv.Category = cate;
                inv.StyleId = styleNo;
                inv.Quantity = quantity;
                inv.Date = date;
                inv.Description = desc;
                inv.SalePrice = SalePrice;
                inv.Weight = weight;
                inv.ImportPrice = unitCost;
                inv.InvoiceNo = invoiceNo;
                inv.MemoNo = memoNo;
                inv.ItemNo = itemNo;
                inv.StyleNo = supStyleNo;
                inv.Name = name;
                inv.Volume = volume;
                if (!string.IsNullOrEmpty(image) || image.Equals("noimage"))
                    inv.Image = image;
                inv.TotalPrice = totalPrice;
                DataEntities.SaveChanges();
                return true;
            }
            catch (Exception)
            {
                MessageBox.Show(Constants.Msg.ConnectError);
                return false;
            }
        }
        public bool UpdateItem(string id, int quantity)
        {
            try
            {
                var inv = new Inventory();
                inv = GetInventoryByElements(id);
                if (inv == null)
                {
                    MessageBox.Show(Constants.Msg.NotItemExist);
                    return false;
                }
                inv.Quantity = quantity;
                DataEntities.SaveChanges();
                return true;
            }
            catch (Exception)
            {
                MessageBox.Show(Constants.Msg.ConnectError);
                return false;
            }
        }
        public bool AddDuplicatedItem(string id, int quantity)
        {
            try
            {
                var inv = new Inventory();
                inv = GetInventoryByElements(id);
                if (inv == null)
                {
                    MessageBox.Show(Constants.Msg.NotItemExist);
                    return false;
                }
                int currentQty;
                try
                {
                    currentQty = Convert.ToInt32(Convert.ToString(inv.Quantity));
                }
                catch (FormatException)
                {
                    currentQty = 0;
                }

                inv.Quantity = currentQty + quantity;
                //inv.Weight = weight;

                DataEntities.SaveChanges();
                return true;
            }
            catch (Exception)
            {
                MessageBox.Show(Constants.Msg.ConnectError);
                return false;
            }
        }

        public bool DeleteItem(string id)
        {
            try
            {
                var inv = new Inventory();
                inv = GetInventoryByElements(id);
                if (inv == null)
                {
                    MessageBox.Show(Constants.Msg.NotItemExist, "Chú ý");
                    return false;
                }
                DataEntities.DeleteObject(inv);
                DataEntities.SaveChanges();
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(Constants.Msg.ConnectError);
                return false;
            }
        }
        public void DeleteItem(string[] ids)
        {
            try
            {
                foreach (var id in ids)
                {
                    var inv = new Inventory();
                    inv = GetInventoryByElements(id);
                    if (inv != null)
                        DataEntities.DeleteObject(inv);
                }
                DataEntities.SaveChanges();
            }
            catch (Exception ex)
            {
                MessageBox.Show(Constants.Msg.ConnectError);
            }
        }

        public bool DeleteAll()
        {
            try
            {
                var list = GetAllInventory();
                foreach (Inventory item in list)
                {
                    DataEntities.DeleteObject(item);
                }

                DataEntities.SaveChanges();
            }
            catch (Exception)
            {
                return false;
            }

            return true;
        }

        public bool IsExist(Inventory input)
        {
            if (input == null)
                return false;
            var itemId = input.ID;
            try
            {
                var output = DataEntities.Inventories.Where(a => a.ID.ToLower() == itemId.ToLower());
                return output != null && output.Count() > 0 ? true : false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(Constants.Msg.ConnectError);
            }

            return false;
        }
    }
}
